package code.concurrent;

import java.util.concurrent.Semaphore;

// 写三个线程打印 "ABC"，⼀个线程打印 A，⼀个线程打印 B，⼀个线程打印 C，⼀共打印 10 轮。
public class ABCPrinter {
    private int maxCount;

    public ABCPrinter(int _maxCount) {
        maxCount = _maxCount;
    }

    // 从线程A开始执行
    private final Semaphore semaphoreA = new Semaphore(1);
    private final Semaphore semaphoreB = new Semaphore(0);
    private final Semaphore semaphoreC = new Semaphore(0);

    public void printA() {
        print("A", semaphoreA, semaphoreB);
    }

    public void printB() {
        print("B", semaphoreB, semaphoreC);
    }

    public void printC() {
        print("C", semaphoreC, semaphoreA);
    }

    private void print(String s,Semaphore cur, Semaphore next) {
        for(int i=1; i<=maxCount; i++) {
            try {
                cur.acquire();
                System.out.println(Thread.currentThread().getName() + ": " + s);
                // 传递信号给下一个线程
                next.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ABCPrinter p = new ABCPrinter(10);
        new Thread(p::printA, "Thread A").start();
        new Thread(p::printB, "Thread B").start();
        new Thread(p::printC, "Thread C").start();
    }
}
